package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.loan

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.event.IAnalyticsEvent
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util.AnalyticsUtil
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

class LoanGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<LoanGhanaResult>()
    val pageDetailResult: LiveData<LoanGhanaResult> = _pageDetailResult

    private val _createLoanResult = MutableLiveData<LoanGhanaCreateLoanResult>()
    val createLoanResult: LiveData<LoanGhanaCreateLoanResult> = _createLoanResult

    private val _mainProcessResult = MutableLiveData<LoanGhanaMainProcessResult>()
    val mainProcessResult: LiveData<LoanGhanaMainProcessResult> = _mainProcessResult

    private val _nextRouterResult = MutableLiveData<LoanGhanaNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<LoanGhanaNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    /** 选择的金额 */
    var sliderAmount: String = ""

    /** 获取页面详情接口 */
    fun pageDetail() {
        _loadingResult.value = true
        if (this.sliderAmount.isBlank()) {
            _loadingResult.value = false
            _pageDetailResult.value = LoanGhanaResult(error = "Amount is null")
            return
        }

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "GBlsPFiNuJvu9jPOX1NyMw"
        action["amount"] = this.sliderAmount

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()

                // 金额字段
                val amount = obj.optString("amount", "0")

                // 转成不带.0结尾的值
                val amountBigString = BigDecimal(amount).stripTrailingZeros().toPlainString()

                // 更新
                obj.put("amount", amountBigString)

                val list = mutableListOf<JSONObject>()
                val array = obj.optJSONArray("detailItemList") ?: JSONArray()
                for (index in 0 until array.length()) {
                    val item = array[index] as JSONObject
                    list.add(item)
                }

                _pageDetailResult.value = LoanGhanaResult(success = obj, list = list)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _pageDetailResult.value = LoanGhanaResult(error = errMsg)
            }
        })
    }

    /** 提交申请接口 */
    fun createLoan() {
        _loadingResult.value = true
        if (this.sliderAmount.isBlank()) {
            _loadingResult.value = false
            _createLoanResult.value = LoanGhanaCreateLoanResult(error = "Amount is null")
            return
        }

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "v6LmusEyJtnlbynn2ma1t6A"
        action["amount"] = this.sliderAmount

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                _createLoanResult.value = LoanGhanaCreateLoanResult(success = obj)

                try {
                    AnalyticsUtil.addEvent(IAnalyticsEvent.AT_LOAN_APPLY)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _createLoanResult.value = LoanGhanaCreateLoanResult(error = errMsg)
            }
        })

    }

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = LoanGhanaMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value = LoanGhanaMainProcessResult(error = errMsg)
            }
        })
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat(fromCreateLoan = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                LoanGhanaNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }
}